package tv.accedo.achi.dao;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;

import tv.accedo.achi.model.User;

@Component
public class UserDao {

	private SessionFactory sessionFactory; // injection
	private User user; // injection

	/**
	 * Get unique User object by user name
	 * @param username
	 * @return User
	 */
	public User getUserByUsername(String username) {
		Session session = null; 
		try {
//			session = SessionFactoryUtil.getSessionFactory().openSession(); 
			session = sessionFactory.openSession();
			Query query = session.createQuery("from User user where user.username = ?")
					.setParameter(0, username); 
			user = (User) query.uniqueResult(); 
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
//			SessionFactoryUtil.closeSession(session);
			session.close();
		}
		return user; 
	}
	
	/**
	 * Get all user objects from database table 't_user'
	 * @return User List
	 */
	public List<User> getAllUsers() {
		List<User> userList = new ArrayList<User>(); 
		Session session = null; 
		try {
//			session = SessionFactoryUtil.getSessionFactory().openSession(); 
			session = sessionFactory.openSession();
			Query query = session.createQuery("from User user order by user.score asc");
			userList = query.list(); 
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
//			SessionFactoryUtil.closeSession(session);
			session.close();
		}
		return userList; 
	}
	
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Resource
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public User getUser() {
		return user;
	}

	@Resource
	public void setUser(User user) {
		this.user = user;
	}


}
